package com.itheima.service;

import com.itheima.common.R;
import com.itheima.mapper.AddressbookMapper;
import com.itheima.pojo.Addressbook;
import com.itheima.pojo.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author Envy
 */
@Service
public class AddressbookService {
    @Resource
    private AddressbookMapper addressbookMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置默认收货地址
     */
    public Addressbook defaultAddressBook(Addressbook addressbook) {
        //获取到旧默认地址对象将状态改为0(非默认地址)
        Addressbook addressbook1 = addressbookMapper.selectIsDefault();
        if (addressbook1 != null) {
            addressbook1.setIsDefault(0);
            //修改为0之后更新到数据库
            addressbookMapper.defaultAddressBook(addressbook1);
        }
        addressbook.setIsDefault(1);
        Integer integer = addressbookMapper.defaultAddressBook(addressbook);
        if (integer>0){
            return addressbook;
        }
        return null;
    }


    /**
     * 获取默认收货地址
     */
    public Addressbook selectIsDefault() {
        return addressbookMapper.selectIsDefault();
    }

    /**
     * 获取收货地址列表
     */
    public List<Addressbook> selectAddressBook() {
        return addressbookMapper.selectAddressBook();
    }

    /**
     * 根据id获取收货地址
     */
    public Addressbook selectById(String id) {
        return addressbookMapper.selectById(id);
    }

    /**
     * 添加收货地址
     */
    public int addAddressBook(Addressbook addressbook) {
        //获取时间戳,将时间戳作为id
        long timeMillis = System.currentTimeMillis();
        String id = timeMillis + "";
        addressbook.setId(id);
        //获取用户对象
        User user = (User) redisTemplate.opsForValue().get("token");
        //设置地址用户id
        addressbook.setUserId(user.getId());

        return addressbookMapper.addAddressBook(addressbook);
    }

    /**
     * 删除收货地址
     */
    public R<Object> deleteAddressBook(List<String> ids) {
        for (String id : ids) {
            addressbookMapper.deleteAddressBook(id);
        }
        return R.success("删除成功");
    }

    /**
     * 修改收货地址
     */
    public int updateAddressBook(Addressbook addressbook) {
        return addressbookMapper.updateAddressBook(addressbook);
    }
}
